package com.cimr.comm.listenter;


import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.cimr.comm.util.ConfUtil;
import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.plugin.MongoPlugin;
import com.mongodb.MongoClient;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import java.util.Objects;

/**
 * Created by liqi on 2018/3/14.
 * liqiwork@qq.com
 */
public class StartupListener extends HttpServlet implements ServletContextListener {
    private final static Log log = LogFactory.get();
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        String mongoSwitch = ConfUtil.getConf("mongo.switch");
        if (Objects.equals("open", mongoSwitch)) {
            MongoPlugin mongoPlugin = new MongoPlugin();
            String hosts = ConfUtil.getConf("mongo.replica.hosts");
            String[] hostsArray = StrUtil.split(hosts,";");
            for (int i = 0; i < hostsArray.length; i++) {
                String ip = StrUtil.subBefore(hostsArray[i],":",true);
                String port = StrUtil.subAfter(hostsArray[i],":",true);
                mongoPlugin.add(ip, Integer.parseInt(port));
            }
            mongoPlugin.setDatabase(ConfUtil.getConf("mongo.dbName"));
            mongoPlugin.auth(ConfUtil.getConf("mongo.username"), ConfUtil.getConf("mongo.password"));
            MongoClient client = mongoPlugin.getMongoClient();
            MongoKit.INSTANCE.init(client, mongoPlugin.getDatabase());


//            MongoPlugin mongoPlugin=new MongoPlugin();
//            mongoPlugin.add("175.6.4.141",27017);
//            mongoPlugin.setDatabase("iot");
//            mongoPlugin.auth("iot","iot123456");
//            MongoClient client = mongoPlugin.getMongoClient();
//            MongoKit.INSTANCE.init(client, mongoPlugin.getDatabase());
//            client.close();
            Console.log("==========started mongodb============");
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        log.warn("==============================================");
    }
}
